package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jzo2o.common.enums.EnableStatusEnum;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2025-03-01
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {
    @Resource
    private ServeItemMapper serveItemMapper;
    @Resource
    private RegionMapper regionMapper;
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOS) {
        // 批量添加需要遍历每一个服务项
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOS) {
            // 合法性校验 serve_item是否启用，如果没有启用 不能添加
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if(ObjectUtils.isNull(serveItem)|| serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
               // 抛出异常
                throw new ForbiddenOperationException("服务项不存在或者未启用,不允许添加");
            }

            // 同一个区域下不能添加相同的服务项
            // sql: select count(*) from serve where serve_item_id =? and region_id = ?
            // new LambdaUpdateWrapper<Serve>()
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId,serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId,serveUpsertReqDTO.getServeItemId())
                    .count();
            if(count>0){
                throw new ForbiddenOperationException("该区域下已经添加过该服务项");
            }

            // 新增服务
            // 将服务请求DTO转换为服务实体
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serve.getRegionId());
            String cityCode = region.getCityCode();
            serve.setCityCode(cityCode);
            // 向serve中插入数据
            baseMapper.insert(serve);
        }

    }

    @Override
    @Transactional
    public Serve update(Long id, BigDecimal price) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getPrice,price)
                .update();
        if(!update){
            throw new ForbiddenOperationException("修改服务价格失败");
        }
        // 查询serve数据
        return baseMapper.selectById(id);

    }

    @Override
    @Transactional
    public Serve onSale(Long id) {
        Serve serve = baseMapper.selectById(id); // 首先查询服务
        if(ObjectUtils.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        // 区域服务状态
        Integer saleStatus = serve.getSaleStatus();
        // 草稿或下架状态可上架
        if(!(saleStatus== FoundationStatusEnum.INIT.getStatus()||saleStatus== FoundationStatusEnum.DISABLE.getStatus())){
            throw new ForbiddenOperationException("草稿或下架状态可上架");
        }
        // 服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtils.isNull(serveItem)){
            throw new ForbiddenOperationException("服务项不存在");
        }
        // 服务项状态
        Integer activeStatus = serveItem.getActiveStatus();
        // 服务项启用状态方可上架
        if(!(activeStatus== FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("服务项启用状态方可上架");
        }
        // 更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new ForbiddenOperationException("更新上架状态失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional
    public Serve offSale(Long id) {
        Serve serve = baseMapper.selectById(id); // 首先查询服务
        if(ObjectUtils.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        // 区域服务状态
        Integer saleStatus = serve.getSaleStatus();
        if(!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("上架状态可下架");
        }
        // 更新下架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId,id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new ForbiddenOperationException("更新下架状态失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public void deleteById(Long id) {
        // 首先查找服务
        Serve serve = baseMapper.selectById(id);
        // 如果没有服务
        if(ObjectUtils.isNull(serve)){
            throw new ForbiddenOperationException("该区域服务不存在");
        }
        // 草稿状态可删除
        if(serve.getSaleStatus()!= FoundationStatusEnum.INIT.getStatus()){
            throw new ForbiddenOperationException("草稿状态方可删除");
        }
        // 删除服务
        baseMapper.deleteById(id);
    }

    /**
     * 设置服务为热门
     * 仅当服务当前不是热门状态时，可以将其设置为热门
     *
     * @param id 服务ID
     * @return 更新后的服务对象
     * @throws ForbiddenOperationException 如果服务已经是热门状态，则抛出此异常
     */
    @Override
    @Transactional
    public Serve onHot(Long id) {
        // 仅当非热门状态可设置
        Serve serve = baseMapper.selectById(id);
        if(serve.getIsHot()== EnableStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("非热门状态方可设置");
        }
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationStatusEnum.ENABLE.getStatus())
                .set(Serve::getHotTimeStamp, System.currentTimeMillis())
                .update();
        if(!update){
            throw new ForbiddenOperationException("更新热门状态失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 取消服务的热门状态
     * 仅当服务当前是热门状态时，可以将其取消为热门
     *
     * @param id 服务ID
     * @return 更新后的服务对象
     * @throws ForbiddenOperationException 如果服务已经不是热门状态，则抛出此异常
     */
    @Override
    public Serve offHot(Long id) {
        // 仅当热门状态可取消
        Serve serve = baseMapper.selectById(id);
        if(serve.getIsHot()!= FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("热门状态方可取消");
        }
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, EnableStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new ForbiddenOperationException("更新热门状态失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 根据区域ID和销售状态查询服务数量
     *
     * @param id 区域ID
     * @param status 销售状态，如果非空，则根据此状态过滤服务
     * @return 符合条件的服务数量
     */
    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long id, int status) {
        return lambdaQuery().eq(Serve::getRegionId, id)
                .eq(ObjectUtils.isNotEmpty(status),Serve::getSaleStatus, status)
                .count();
    }

    @Override
    public int queryServeCountByServeItemIdAndSaleStatus(Long id, int status) {
        return lambdaQuery().eq(Serve::getServeItemId, id)
                .eq(ObjectUtils.isNotEmpty(status),Serve::getSaleStatus, status)
                .count();
    }
}
